package com.hontech.bread.utils


import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.SystemClock
import android.view.inputmethod.InputMethodManager
import com.hontech.bread.R
import com.hontech.bread.app.AppContext
import java.io.PrintWriter
import java.net.NetworkInterface
import java.util.Locale

private const val MAC_IF_NAME = "eth0"

private fun getMac(): String {

    try {
        val ns = NetworkInterface.getNetworkInterfaces()
        for (n in ns) {
            val hard = n.hardwareAddress ?: continue
            if (n.name == MAC_IF_NAME) {
                return hard.formatMac()
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return "${stringById(R.string.t1733460848_472)}"
}

val macAddr = getMac()

const val APP_ID = "com.hontech.bread"

suspend fun wifiRestart() {
//    log("wifi ${stringById(R.string.t1733460848_473)}")
//    val wifiManager = AppContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//    wifiManager.isWifiEnabled = false
//    delay(1000)
//    wifiManager.isWifiEnabled = true
//    delay(3000)
}

fun hideSoftKey(activity: Activity) {
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (!imm.isActive) {
        return
    }
    val view = activity.currentFocus ?: return
    imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

val PackageName = AppContext.packageName
val Version = AppContext.packageManager.getPackageInfo(PackageName, 0).versionName
val Width = AppContext.resources.displayMetrics.widthPixels
val Height = AppContext.resources.displayMetrics.heightPixels

fun isBigScreen() = Width > 900

fun installApk2(path: String) {
    val rt = Runtime.getRuntime()
        .exec("su")

    val pw = PrintWriter(rt.outputStream)
    pw.println("pm install -r -t $path")
    pw.flush()
    pw.close()
    val v = rt.waitFor()

    if (v != 0) {
        throw IllegalStateException(
            "${stringById(R.string.t1733460848_474)}root${stringById(R.string.t1733460848_475)} ${
                stringById(
                    R.string.t1733460848_476
                )
            }"
        )
    }
}


private fun rootGrantPermission(name: String) {
    val runtime = Runtime.getRuntime()
        .exec("su")

    val pw = PrintWriter(runtime.outputStream)
    pw.write("pm grant $APP_ID $name")
    pw.flush()
    pw.close()
    val v = runtime.waitFor()
    if (v != 0) {
        throw IllegalStateException(
            "${stringById(R.string.t1733460848_477)}root${stringById(R.string.t1733460848_478)} ${
                stringById(
                    R.string.t1733460848_479
                )
            }${name}"
        )
    }
}

private fun checkPermission(name: String): Boolean {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true
    }
    val ret = AppContext.checkSelfPermission(name)
    return ret == PackageManager.PERMISSION_GRANTED
}

suspend fun grantPermission(name: String) {
    if (checkPermission(name)) {
        return
    }
    runCPU { rootGrantPermission(name) }
}


fun stringById(id: Int) = AppContext.resources.getString(id)
fun stringsById(id: Int) = AppContext.resources.getStringArray(id)
fun dimenById(id: Int) = AppContext.resources.getDimension(id).toInt()


// en US
// zh CN
// es ES
fun setLocale(language: String, country: String) {
    log("${stringById(R.string.t1733460848_480)} $language $country")

    val locale = Locale(language, country)
    Locale.setDefault(locale)
    val config = AppContext.resources.configuration
    config.setLocale(locale)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        AppContext.createConfigurationContext(config)
    } else {
        AppContext.resources.updateConfiguration(config, AppContext.resources.displayMetrics)
    }
}

fun restartAppWithDelay() {
    val intent = AppContext.packageManager.getLaunchIntentForPackage(AppContext.packageName)
    val restartIntent = PendingIntent.getActivity(
        AppContext, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT
    )
    val alarmManager = AppContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    alarmManager.set(
        AlarmManager.ELAPSED_REALTIME,
        SystemClock.elapsedRealtime() + 100,
        restartIntent
    )
    Runtime.getRuntime().exit(0) // ${stringById(R.string.t1733460848_481)}
}






























